import Vue from 'vue';
import VueRouter from 'vue-router';
import home from '../homeView.vue';
import login from '../login.vue'
let newroutes = JSON.parse(window.sessionStorage.getItem('routes'))||[]
let newRoute =[]
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
return originalPush.call(this, location).catch(err => err)
}
if(newroutes.length>0){
     newRoute = newroutes.map(v=>{
		return {
			path: v.path,
			name: v.name,
			component: () => import( '../'+v.urlbase),
			meta:v.meta,
		}
	 })
} 
Vue.use(VueRouter);

 const  routes= [
		{
			name:"login",
			path: '/',
			meta:{title:'登录'},
			component: login,
		},
		{
			name:"401",
			path: '/401',
			component: () => import('../401.vue')
		},      
    ]
	const router = new VueRouter({	
		mode: 'hash',
		base:process.env.VUE_APP_MENU_URL,
		scrollBehavior: () => ({ y: 0 }), // 在切换时定位路由滚动条的位置
		routes,
	})
	let hasRoles = true
	router.beforeEach((to,from,next)=>{
         if(to.path!=='/'){
			let nowRoutes = JSON.parse(window.sessionStorage.getItem('routes'))||null
			if(hasRoles&&nowRoutes!=null&&nowRoutes.length>0){
				let newT = {
				    name:"home",
					path: '/home',
					component: home,
					redirect:nowRoutes[0].path,
					children:nowRoutes.map(v=>{
						return {
							path: v.path,
							name: v.name,
							component:() => import( '../'+v.urlbase),
							meta:{
								routerpath:v.routerpath,
								icon:v.icon,
								title:v.title
							},
						}
					 })
				}
				hasRoles=false
				router.addRoute(newT)		
			    next({...to,replace:true})
			}else{
				if(to.name==null){
					return next('/401')
				}else{
					next()
				}
			}
		 }else{
			hasRoles=true
			// console.log(router)
			next()
		 }
	})
export default router
		   